/**
 * @file Define the base handler for all web requests
 * 
 * @author Steve Gao<gaofu@parllay.com>
 */

const utils                 = require('../../utils');
const SystemServices        = require('../../constants').SystemServices;
const HTTP_VERBS            = require('../../constants').HTTP_VERBS;
const ApplicationEvents     = require('../../applications/application').ApplicationEvents;

const {CriticalErrors} = require('../../constants');

/**
 * The base web request handler
 * 
 * @class BaseHandler
 */
class BaseHandler {

    get logger() {
        if (!this._logger) {
            let logService = this.Application.Context.getSystemService(SystemServices.LOG_SERVICE);
            this._logger = logService ? logService.getLogger() : console;
        }

        return this._logger;
    }

    get name() {
        return 'BaseHandler';
    }

    get pattern() {
        return "*";
    }

    get Controller() {
        return this._Controller;
    }

    get Server() {
        return this._Server;
    }

    get Application() {
        return this._Application;
    }

    constructor(controller, server, application) {
        this._IsUnderMaintainancing = false;
        this._Controller = controller;
        this._Server = server;
        this._Application = application;
    }

    /**
     * Register verb handler into Web Server
     * 
     * @name registerVerb
     * @param {String} verb - The HTTP verb
     * @param {Function} handler - The handle function
     * 
     * @returns {Boolean}
     */
    registerVerb(verb, handleFunction) {
        return this.Server.registerRequestVerbHandler(this, verb, handleFunction);
    }

    doGET(request, response) {
        response.redirect('/404');
    }

    doPOST(request, response) {
        response.redirect('/404');
    }

    doPUT(request, response) {
        response.redirect('/404');
    }

    doDELETE(request, response) {
        response.redirect('/404');
    }

    doALL(request, response) {
        response.redirect('/404');
    }

    reportError(error) {
        this.Application.reportError(CriticalErrors.WEB_REQUEST_ERROR, error);
    }

    /**
     * Check the ref parameter and make sure it exists
     * 
     * @name ensureRef
     * @param {IncomingMessage} request - The web request
     * 
     * @returns {void}
     */
    ensureRef(request) {
        if (! request.session.user.refs ) {
            request.session.user.refs = [];
        }

        var ref = request.query.ref || 'direct';

        if (request.session.user.refs.indexOf(ref) >= 0) {
            request.session.user.refs.splice(request.session.user.refs.indexOf(ref), 1);
        }

        request.session.user.refs.push(ref);
    }

    get needAuthenticated() {
        return true;
    }

    setup() {}
}

module.exports = BaseHandler;